﻿using SuperSocket.WebSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace websocket_server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartServer(11200);
        }

        //初始化WebSocket
        private void StartServer(int port)
        {
            WebSocketServer Server = new WebSocketServer();
            Server.NewMessageReceived += Server_NewMessageReceived; ;//当有信息传入时
            Server.NewSessionConnected += WebSocketServer_NewSessionConnected; ;//当有用户连入时
            Server.SessionClosed += WebSocketServer_SessionClosed;  //当有用户退出时
            Server.NewDataReceived += Server_NewDataReceived; ;//当有数据传入时
            Server.Setup(port);//绑定端口
            Server.Start();//启动服务
        }

        //WebSocket可以接收string类型数据，也可以接收byte[]类型数据
        private void Server_NewMessageReceived(WebSocketSession session, string value)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("From ").Append(session.RemoteEndPoint.ToString()).Append(": \r\n")
                .Append(value).Append("\r\n\r\n");
            BeginInvoke(new Action(() =>
            {
                textBox1.AppendText(sb.ToString());
                session.Send("服务端接受["+sb.ToString()+"]成功");
            }));

            //todo  响应数据
            //String ss="whosyourdaddy"; 
            //session.Send(ss);
        }
        private void Server_NewDataReceived(WebSocketSession session, byte[] value)
        {
            Console.WriteLine("有数据传入");
        }
        private void WebSocketServer_NewSessionConnected(WebSocketSession session)
        {

            Console.WriteLine("欢迎客户端： 加入");
            //SendToAll(session, msg);
        }

        private void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            Console.WriteLine("客户端：关闭，原因：");
            //SendToAll(session, msg);
        }



    }
}
